package com.senlingspace.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.senlingspace.common.enums.LakalaResponseCodeEnum;
import com.senlingspace.common.utils.MoneyUtils;
import com.senlingspace.payment.lakala.bean.request.LakalaFeeAmountRequest;
import com.senlingspace.payment.lakala.bean.response.LakalaFeeAmountResponse;
import com.senlingspace.payment.lakala.service.LakalaTransFeeService;
import com.senlingspace.system.domain.SlkjOrder;
import com.senlingspace.system.mapper.SlkjOrderMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * lakala服务费拉取
 *
 * @author lebronjames
 * @date 2024/08/09
 */
@Slf4j
@Component
@AllArgsConstructor
public class LakalaTransFeeTask {

    private final SlkjOrderMapper slkjOrderMapper;
    private final LakalaTransFeeService lakalaTransFeeService;


    @Scheduled(fixedDelay = 3, timeUnit = TimeUnit.MINUTES) // 3分钟一次
    public void feeAmount() {
        log.info("拉卡拉服务费拉取任务开始执行。");
        List<SlkjOrder> orders = slkjOrderMapper.selectOnShopOrderList(null);
        if (CollectionUtils.isNotEmpty(orders)) {
            for (SlkjOrder order : orders) {
                LakalaFeeAmountResponse response = lakalaTransFeeService.feeAmount(new LakalaFeeAmountRequest(order.getThirdOrderNumber(), order.getShopId()));
                log.info("查询商户计费 response:{},orderId={}", JSON.toJSONString(response), order.getOrderId());
                if (Objects.isNull(response) ||
                        Objects.isNull(response.getRespData()) ||
                        Objects.isNull(response.getRespData().getFeeAmount()) ||
                        !response.getCode().equals(LakalaResponseCodeEnum.MERCHANT_QUERY_TRANS_000000.getBriefDescription())) {
                    continue;
                }

                LakalaFeeAmountResponse.RespData data = response.getRespData();
                String settleAmount = data.getSettleAmount();
                settleAmount = settleAmount.replaceAll("^\"|\"$", "");
                int settleAmountHao = MoneyUtils.yuan2Hao(settleAmount);
                order.setSettleAmount(settleAmountHao);

                String feeAmount = data.getFeeAmount();
                feeAmount = feeAmount.replaceAll("^\"|\"$", "");
                int feeAmountHao = MoneyUtils.yuan2Hao(feeAmount);
                order.setFeeAmount(feeAmountHao);
                log.info("订单 [{}] 拉卡拉服务费：{} 毫元，商户最终收款：{} 毫元。", order.getOrderNumber(), feeAmountHao, settleAmountHao);
                slkjOrderMapper.updateOrderFeeAmount(order.getOrderId(), feeAmountHao, settleAmountHao);
            }
        }
        log.info("拉卡拉服务费拉取任务执行完毕。");
    }

}
